package com.pz.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.pz.gulimall.common.constant.ProductConstant;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.to.MemberPrice;
import com.pz.gulimall.common.to.SkuHasStockTo;
import com.pz.gulimall.common.to.SkuReductionTo;
import com.pz.gulimall.common.to.SpuBoundTo;
import com.pz.gulimall.common.to.es.SkuEsModelTo;
import com.pz.gulimall.common.utils.R;
import com.pz.gulimall.product.entity.*;
import com.pz.gulimall.product.feign.CouponFeign;
import com.pz.gulimall.product.feign.SearchFeign;
import com.pz.gulimall.product.feign.WareFeign;
import com.pz.gulimall.product.service.*;
import com.pz.gulimall.product.vo.req.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pz.gulimall.common.utils.PageUtils;
import com.pz.gulimall.common.utils.Query;

import com.pz.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private AttrService attrService;
    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuImagesService skuImagesService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeign couponFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //TODO 错误逻辑处理待完善
    @Transactional  //复杂业务流程开启事务注解，遇到错误就会回滚数据
    @Override
    public void saveSpuInfo(SpuSaveReqVo vo) {
        //1、保存 spu 的基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity  = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.save(spuInfoEntity);

        //2、保存 spu 的 描述图片集 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfoEntity.getId());
        spuInfoDesc.setDecript(String.join(",",decript)); //用逗号分隔List元素并返回一个字符串
        spuInfoDescService.saveSpuinfoDesc(spuInfoDesc);

        //3、保存 spu 的图片集 pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4、保存 spu 的规格参数--pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> list = baseAttrs.stream().map(baseAttr -> {
            ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
            productAttrValue.setSpuId(spuInfoEntity.getId());
            productAttrValue.setAttrId(baseAttr.getAttrId());
            AttrEntity attrEntity = attrService.getById(baseAttr.getAttrId());
            productAttrValue.setAttrName(attrEntity.getAttrName());
            productAttrValue.setAttrValue(baseAttr.getAttrValues());
            productAttrValue.setQuickShow(baseAttr.getShowDesc());

            return productAttrValue;
        }).collect(Collectors.toList());
        if(list.size() > 0){
            productAttrValueService.saveBaseAttrs(list);
        }

        //5、保存spu的积分信息：`gulimall_sms` -- sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R result = couponFeign.savePusBounds(spuBoundTo);
        if(result.getCode() != 0){
            log.error("远程保存spu积分信息失败");
        }

        //6、保存当前 spu 对应的所有sku信息
        List<Skus> skusList = vo.getSkus();
        if(skusList!= null && skusList.size()>0){
            skusList.forEach( item  -> {
                //获取默认图片
                String defaultImgUrl = "";
                for(Images img: item.getImages()){
                    if(img.getDefaultImg() == 1L){
                        defaultImgUrl = img.getImgUrl();
                    }
                }

                //6.1、保存sku的基本信息：pms_sku_info
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImgUrl);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();

                //6.2、保存sku的图片信息：pms_sku_images
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(entity -> {
                    // 返回 true 证明 图片路径 url 不为空保存下来；返回false就剔除
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                if(imagesEntities.size()>0){
                    //TODO 没有图片路径的不能保存
                    skuImagesService.saveBatch(imagesEntities);
                }

                //6.3、保存sku的销售信息 pms_sku_sale_attr_value
                List<Attr> attrList = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities =  attrList.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValue = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);

                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                if(skuSaleAttrValueEntities.size()>0){
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }

                //6.4、保存sku的优惠、满减等信息 --> `gulimall_sms`-- sms_sku_ladder / sms_sku_full_reduction/ sms_member_price
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                if(item.getFullCount() > 0 || item.getFullPrice().compareTo(new BigDecimal(0)) == 1){
                    // 满减数大于0 或 满多少价格才减 这样的数据才有保存的意义
                    BeanUtils.copyProperties(item, skuReductionTo);
                    // BeanUtils.copyProperties 拷贝 List 属性为空，需要深拷贝
                    List<MemberPrice> memberPrices = item.getMemberPrice().stream().map(memberPrice -> {
                        MemberPrice memberPrice1 = new MemberPrice();
                        BeanUtils.copyProperties(memberPrice, memberPrice1);
                        return memberPrice1;
                    }).collect(Collectors.toList());
                    skuReductionTo.setSkuId(skuId);
                    skuReductionTo.setMemberPrice(memberPrices);
                    R result2 = couponFeign.saveSkuReduction(skuReductionTo);
                    if(result2.getCode() != 0){
                        log.error("远程保存sku优惠信息失败");
                    }
                }

            });
        }

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        String catelogId= (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String publishStatus = (String) params.get("status");
        if(key != null && !key.isEmpty()){
            queryWrapper.and( w -> {
                w.eq("id", key).or().like("spu_name", key).or().like("spu_description", key);
            });
        }
        if(catelogId != null && !catelogId.equals("0")) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        if(brandId != null && !brandId.equals("0")){
            queryWrapper.eq("brand_id", brandId);
        }
        if(publishStatus != null){
            queryWrapper.eq("publish_status", publishStatus);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 修改发布状态的同时，将商品添加到 ES 中，以供用户搜索
     * @param spuId
     * @return 保存到 es 并 更新状态成功返回 true
     */
    @Transactional
    @Override
    public void upSpu(Long spuId) {
        //保存ES的数据模型
        skuInfoService.updateSkuEsModel(spuId);
        //保存成功，修改商品状态
        this.update(new UpdateWrapper<SpuInfoEntity>().
                set("publish_status", ProductConstant.SpuInfoPublishStatusEnum.UP.getCode()).
                set("update_time", new Date()).
                eq("id", spuId)
        );
    }

    @Override
    public List<SpuInfoEntity> queryAllPublish() {
        try {
            return this.list(new QueryWrapper<SpuInfoEntity>().eq("publish_status", "1"));
        } catch (Exception e) {
            throw new RRException(BizCodeEnum.MYSQL_EXCEPTION.getMsg(), BizCodeEnum.MYSQL_EXCEPTION.getCode());
        }
    }


}